package com.whz.crypt.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * @author whz
 */
@Data
@ConfigurationProperties(prefix = CryptProperty.PREFIX)
public class CryptProperty {
    public static final String PREFIX = "web.transport.crypt";

    private boolean enable;
    /**
     * 是否打印日志
     */
    private boolean printLog;

    private CryptType cryptType;

    private RsaProperty rsaProperty;

    private AesProperty aesProperty;

    public static enum CryptType {
        AES, RSA;
    }

    @Data
    public static class AesProperty {
        private String secretKey;
    }

    @Data
    public static class RsaProperty {
        /**
         * base64编码的RSA私钥/公钥
         */
        private String key;

        /**
         * 秘钥类型,公钥还是私钥
         */
        private KeyType keyType = KeyType.PRIVATE;
        /**
         * 字符串编码,默认UTF-8
         */
        private Charset charSet = StandardCharsets.UTF_8;

        public static enum KeyType {
            PUBLIC, PRIVATE;
        }
    }

    public void resolvePrivate(final Environment environment) {
        switch (this.cryptType) {
        case AES: {
            String privateKey = environment.resolvePlaceholders(this.aesProperty.getSecretKey());
            if (!StringUtils.isEmpty(privateKey)) {
                this.aesProperty.setSecretKey(privateKey);
            }
        }
        break;
        case RSA: {
            String privateKey = environment.resolvePlaceholders(this.rsaProperty.getKey());
            if (!StringUtils.isEmpty(privateKey)) {
                this.rsaProperty.setKey(privateKey);
            }
        }
        break;
        }
    }
}